//
//  OAuthViewController.swift
//  weibo10
//
//  Created by 周荣硕 on 16/1/10.
//  Copyright © 2016年 grgbanking. All rights reserved.
//

import UIKit

//用户登录控制器
class OAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    //MARK: 监听方法
    
    @objc private func close(){
    
        dismissViewControllerAnimated(true, completion: nil)
    }
///  自动填充用户名和密码 --web注入（以代码的方式向web页面添加内容）
    @objc private func autoFill(){
//    
//        let js = "document.getElementById('userId').value = '15652349475';" + "docment.getElementById('passwd').value = 'zrshuo361376';"
        let js = "document.getElementById('userId').value = '15652349475';" +
        "document.getElementById('passwd').value = 'zrshuo361376';"

        
        //让webView执行js
        
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    
    //MARK:设置界面 
    
    override func loadView() {
        view = webView
        
         webView.delegate = self
    //设置导航栏
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style:.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        view.backgroundColor=UIColor.whiteColor()
        //加载页面 
        
        self.webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))

       
    }
}
// MARK: - UIWebViewDelegate
extension OAuthViewController:UIWebViewDelegate{

    
    ///  将要加载请求的代理方法
    ///
    ///  - parameter webView:        webView
    ///  - parameter request:        request
    ///  - parameter navigationType: navigationType  页面跳转的方式
    ///
    ///  - returns: 返回false不加载 返回true 加载
    /// 如果 iOS 的代理方法中有返回 bool，通常返回 true 很正常，返回 false 不能正常工作

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //1.判断访问的主机是否是百度
        guard let url = request.URL where url.host == "www.baidu.com" else{
        
            return true
        }
        //2.从百度地址的URL提取 code ==是否存在
        // 2. 从百度地址的 url 中提取 `code=` 是否存在
        guard let query = url.query where query.hasPrefix("code=") else {
            print("取消授权")
            
            return false
        }
        
        // 3. 从 query 字符串中提取 `code=` 后面的授权码
        let code = query.substringFromIndex("code=".endIndex)
        
        print(query)
        print("授权码是 " + code)

        //4.加载 accessToken
        UserAccountViewModel.sharedUserAccount.loadAccessToken(code) { (isSuccessed) -> () in
            if isSuccessed {
                print("成功了")
                print(UserAccountViewModel.sharedUserAccount.account)
            } else {
                print("失败了")
            }

        }
        
    
    
        return false
        
    }
}
    

    
    

